package cn.bellychang.leetcode.question347;

import java.util.HashMap;
import java.util.Map;
import java.util.PriorityQueue;

/**
 * @author ChangLiang
 * @date 2021/3/17
 */
public class Solution {

    public int[] topKFrequent(int[] nums, int k) {

        int[] result = new int[k];

        PriorityQueue<Node> priorityQueue = new PriorityQueue<>(nums.length, (node1, node2) -> {
            if (node1.count > node2.count) {
                return -1;
            } else if (node1.count < node2.count) {
                return 1;
            } else {
                return 0;
            }
        });

        HashMap<Integer, Integer> hashMap = new HashMap<>();

        for (int num : nums) {
            if (hashMap.containsKey(num)) {
                hashMap.put(num, hashMap.get(num) + 1);
            } else {
                hashMap.put(num, 1);
            }
        }

        for (Map.Entry<Integer, Integer> entry : hashMap.entrySet()) {
            Node node = new Node(entry.getKey(), entry.getValue());
            priorityQueue.add(node);
        }

        for (int i = 0; i < k; i++) {
            result[i] = priorityQueue.poll().value;
        }

        return result;
    }

    class Node{
        int value;
        int count;

        public Node(int value, int count) {
            this.value = value;
             this.count = count;
        }
    }
}
